// pages/absence/apply/index.ts
import AbsenceApi from "../../../api/AbsenceApi"
import Toast from "tdesign-miniprogram/toast/index"
import { formatDate } from "../../../utils/util"

Page({
  /**
   * 页面的初始数据
   */
  data: {
    typeText: '请选择',
    rangeText: '请选择',
    remark: '',
    typeValue: [],
    typeList: [
      { label: '调休', value: '0' },
      { label: '年假', value: '1' },
      { label: '事假', value: '2' },
      { label: '病假', value: '3' },
      { label: '婚假', value: '4' },
      { label: '产假', value: '5' },
      { label: '陪产假', value: '6' },
      { label: '哺乳假', value: '7' },
      { label: '丧假', value: '8' },
    ],
    startTime: "",
    endTime: ""
  },
  onPickerChange(e: any) {
    const { key } = e.currentTarget.dataset
    const { label, value } = e.detail
    this.setData({
      [`${key}Visible`]: false,
      [`${key}Value`]: value,
      [`${key}Text`]: label.join(' '),
    })
  },
  onPickerCancel(e: any) {
    const { key } = e.currentTarget.dataset
    this.setData({
      [`${key}Visible`]: false,
    })
  },
  onTypePicker() {
    this.setData({ typeVisible: true })
  },
  handleCalendar() {
    this.setData({ rangeVisible: true })
  },
  handleConfirmRange(e: any) {
    const { value } = e.detail

    const _this = this
    const format = ([start, end]: number[]) => {
      const date1 = new Date(start)
      _this.setData({ startTime: formatDate(date1) })
      let s = `${formatDate(date1).replace(/-/g, '.')}`
      if (end) {
        const date2 = new Date(end)
        s += `-${formatDate(date2).replace(/-/g, '.')}`
        _this.setData({ endTime: formatDate(date2) })
      } else {
        _this.setData({ endTime: formatDate(date1) })
      }
      return s
    }
    this.setData({
      rangeText: format(value),
    })
  },
  handleConfirm() {
    const { startTime, endTime, typeValue, remark } = this.data
    AbsenceApi.save({ startTime, endTime, type: typeValue[0], remark }).then(_ => {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '提交成功',
        theme: 'success',
        direction: 'column',
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 300)
    }).catch(e => {
      Toast({
        context: this,
        selector: '#t-toast',
        message: e,
      })
    })
  },
})
